<?php 
class Controller extends Controller_Core
{
	public $db;
	public $session;
	public $site;
	public $sess_cus;
	public $sess_user;
	public $cart;
	public $items;
	public $str_pattern = "<#>";
    public $login_model;
	
    public function __construct()
    {
        parent::__construct();
        $this->db = Database::instance();
        $this->session = Session::instance();
        
        //Model
        $this->login_model = new Login_Model();
        
        //Site
		$this->get_site();
		//$this->set_sess_history();
		//Client or admin
        if(strpos($this->uri->segment(1),"admin") === false){						
			$this->init_client();
		} else
			$this->init_admin();		
    }
 	
    public function do_something()
    {
        // method available in all controllers 		
    }
    
    public function get_site()
    {
		$model = new Site_Model();
		$this->site = $model->get();
		
	}
	
	public function set_sess_history()
	{
		//Get history back from session if have
		if ($this->session->get('sess_his_back'))
		{    
			$this->site['history'] = $this->session->get('sess_his_back');
			if ($this->_check_url_valid($this->site['history']))
			{
			$this->site['history']['back'] = $this->site['history']['current'];
			$this->site['history']['current'] = url::current(true);
			}
			$this->session->set('sess_his_back',$this->site['history']);
		}
		else
			$this->session->set('sess_his_back', array('back' => url::current(true),'current' => url::current(true)));
	}
	
	private function _check_url_valid($history)
	{
		if ($history['current'] == url::current(true))
			return FALSE;
		if (strpos(url::current(true),'save') !== FALSE)
			return FALSE;
		if (strpos(url::current(true),'delete') !== FALSE)
			return FALSE;
		return TRUE;
	}
	
    public function get_view()
    {
		$this->load_quick_cart();
        $this->load_search();
	}
	public function get_events()
    {
		$language_id = $this->get_client_lang();
		$model = new Programs_Model(); 
		$this->db->limit(10,0);	
		$mEventList = $model->get_with_active($language_id);
		return $mEventList;
	}
	public function get_testimonial()
    {
		$language_id = $this->get_client_lang();
		$model = new Testimonials_Model(); 
		$this->db->limit(4,0);	
		$mTestimonials = $model->get_with_active($language_id);
		return $mTestimonials;
	}
    public function list_language()
    {
		$model = new Language_Model();
		return $model = $model->get_with_active($this->get_client_lang());
	}
    
	public function init_client()
	{
		$this->set_sess_history();
		//Url
        $this->site['base_url'] = url::base();
        $this->site['theme_url'] = url::base().'themes/style/';
        //Config
        if($this->session->get('sess_client_lang_code'))
        	Kohana::config_set('locale.language', array($this->session->get('sess_client_lang_code')));
        //Sess
        $this->sess_cus = $this->login_model->get_login(1);
	} 
    
	public function init_admin()
	{
		//Url
		$this->site['base_url'] = url::base();
		$this->site['theme_url'] = url::base().'themes/admin/';
		
		//Config
		Kohana::config_set('locale.language', array('en_US'));
		/*if($this->session->get('sess_admin_lang_code'))
        	Kohana::config_set('locale.language', array($this->session->get('sess_admin_lang_code')));*/
		//Get controller
		$this->site['controller'] = $this->uri->segment(1,'both');
		
		if($this->uri->segment(1) != "admin_login")	{
			if(!$this->login_model->is_login(2))
			{
				url::redirect('admin_login');
				die();
			}
			//Sess
			$this->sess_user = $this->login_model->get_login(2);
		}		
	}  
	
    public function get_breadcrumbs()
	{
		global $breadcrumbs;
	 
		$get_breadcrumbs = html::breadcrumb();
		while(current($get_breadcrumbs))
		{
			// Check if we have reached the last crumb
			if(key($get_breadcrumbs) < (count($get_breadcrumbs)-1))
			{
				// If we haven't, add a breadcrumb separator
				$breadcrumbs .= current($get_breadcrumbs).' :: ';
			} else {
				// If we have, remove the anchor from the breadcrumb and make it bold
				$breadcrumbs .= strip_tags("<strong>".current($get_breadcrumbs)."</strong>", "<strong>");
			}
			next($get_breadcrumbs);
		}
		return $breadcrumbs;
	}
	
	public function list_page()
	{
		$list_page = '';
		$model = new Article_content_Model();
		$this->db->where('languages_id',$this->get_client_lang());
		$list = $model->get_article();
    	for($i=0; $i<count($list); $i++){
    		$list_page .= '<td><a href="'.url::base().'article/detail/'.$list[$i]['articles_content_id'].'">'.$list[$i]['articles_title'].'</a></td>';
   		}
   		return $list_page;
	}
	
	public function get_banner()
	{
		$str = '';
		if(strpos($_SERVER['REQUEST_URI'],'register'))
			$str = '<img src="'.url::base().'themes/style1/index/pics/banner_register.jpg" align="middle"/>';
		elseif(strpos($_SERVER['REQUEST_URI'],'login'))
			$str = '<img src="'.url::base().'themes/style1/index/pics/banner_login.jpg" align="middle"/>';
		elseif(strpos($_SERVER['REQUEST_URI'],'product'))
			$str = '<img src="'.url::base().'themes/style1/index/pics/banner_product.jpg" align="middle"/>';
		elseif(strpos($_SERVER['REQUEST_URI'],'contact'))
			$str = '<img src="'.url::base().'themes/style1/index/pics/banner_contact.jpg" align="middle"/>';
		elseif(strpos($_SERVER['REQUEST_URI'],'login'))
			$str = '<img src="'.url::base().'themes/style1/index/pics/banner_login.jpg" align="middle"/>';
		else
			$str = '<img src="'.url::base().'themes/style1/index/pics/banner.jpg" align="middle"/>';
		return $str;
	}
	
	public function set_config($str_lang)
	{	
		switch($str_lang){					
			default:
				//'english'		
		};		
	}
		
	
	
	public function load_search()
	{
		$str='';
		$language_id = $this->get_client_lang();
		
		$root_cate = ORM::factory('category')->__get('root');
		$root_children = ORM::factory('category',$root_cate->categories_id)->__get('descendants');
		
		$list_catsearch = array();
        $i=0;
		foreach($root_children as $children){
			$arr_where = array('categories_id'=>$children->categories_id,'languages_id'=>$language_id);
			$children_name = ORM::factory('category_description')->where($arr_where)->find()->categories_name;
			$children_id = ORM::factory('category_description')->where($arr_where)->find()->categories_id;
			$list_catsearch[$i]['id'] = $children_id;
			$list_catsearch[$i]['name'] = $children_name;
			$i++;
		}
		$this->template->list_catsearch = $list_catsearch;
	}
	
	public function list_advertisement($position)
	{
		$arrAdv = ORM::factory('advertisement')->get_with_active($position);
		return $arrAdv; 
	}
	
	/*public function list_category()
	{
		$str="";
		$langue = $this->get_client_lang();
		$categories = ORM::factory('category')->where('categories_parent_id',0)->find_all();
		$str .= '<ul id="treemenu1" class="treeview">';
		foreach($categories as $cate)
		{
			$descategories = ORM::factory('category_description')->where('categories_id',$cate->categories_id)->where('languages_id',$langue)->find_all();
			
			foreach($descategories as $descate)
			{
			$str .= '<li><a href="javascript:;">';
			$str .= $descate->categories_name;
			$str .='</a><ul>';
			}
			
			$subcate = ORM::factory('category')->where('categories_parent_id',$descate->categories_id)->find_all();
			{
				foreach($subcate as $subcate)
					{
						
						$desubcate = ORM::factory('category_description')->where('categories_id',$subcate->categories_id)->where('languages_id',$langue)->find_all();
						foreach($desubcate as $dessubcate )
						{
							$str .= '<li><a href="'.url::base().'product/cate/'.$dessubcate->categories_id.'">';
							$str .= $dessubcate->categories_name;
							$str .='</a><ul>';						
						
						$children = ORM::factory('category')->where('categories_parent_id',$subcate->categories_id)->find_all();
						foreach($children as $children)
						{
								$deschildren = ORM::factory('category_description')->where('categories_id',$children->categories_id)->where('languages_id',$langue)->find_all();
								foreach($deschildren as $children)
								{
									$str .= '<li><a href="'.url::base().'product/cate/'.$children->categories_id.'">';
									$str.=$children->categories_name;
									$str .='</a></li>';
								}
						}
					
						$str .= '</ul>';
						$str .='</li>';					
					}				
					}
			}
			$str .='</ul>';
			$str .='</li>';
		}
		$str .= '</ul>';
		return $str; 
	}*/
  
	//------------ Login ------------
    /*
	public function get_obj($obj)
	{		
		if($obj == 1)	
			$this->obj = 'sess_cus';
		elseif($obj == 2)	
			$this->obj = 'sess_user'; //admin
	}
	
	public function is_login($obj = 1)
	{		
		$this->get_obj($obj);
		
		if($this->session->get($this->obj))
			return TRUE;
		else
			return FALSE;
	}
	
	function get_login($obj = 1)
	{		
		$this->get_obj($obj);
		
		if ($this->session->get($this->obj)) {
			return $this->session->get($this->obj);
		}
		
		return false;
	}
	
	function set_login($obj=1, $val)
	{		
		$this->get_obj($obj);
		$this->session->set($this->obj,$val);
	}
	
	function unset_login($obj=1)
	{		
		$this->get_obj($obj);
		
		$this->session->delete($this->obj);
	}
    */
	//------------ Cart ------------	
	public function get_itemval($product_ord)
	{
		$str_val = $this->items[$product_ord];

		return $a_val = explode($this->str_pattern,$str_val);
	}
	
	public function total_items()
	{
		return count($this->items);
	}	
	
	public function count_products()
	{
		$total_item = 0;
		foreach($this->items as $order=>$val){
		    $total_item++;
		}
		return $total_item;
	}
	
  	public function add_item($item_id,$qty,$name,$price,$weight='',$comment='')
    {
        $qty = (int)$qty;
	    if(!$qty) return;

		$a_val[0] = $item_id;
		$a_val[1] = $qty;
		$a_val[2] = $name;
		$a_val[3] = $price;
		$a_val[4] = $weight;
		$a_val[5] = $comment;

		$str_val = implode($this->str_pattern, $a_val); 
		$this->items[] = $str_val;
    }
	
	public function remove_item($product_ord)
    {
       if(array_key_exists($product_ord, $this->items))
       {
			unset($this->items[$product_ord]);
       }
    }
	
	public function update_comp_item($product_ord,$comp,$val)
    {
	   if($product_ord === "eolst")
	   {
	   		end($this->items);
			$product_ord =  key($this->items);
	   }

       if(array_key_exists($product_ord, $this->items))
       {
			//update item qty
			if($comp == 1){
			if(!is_numeric($val) || $val < 0 || $val != (int)$val) return;
			if($val == 0){
				unset($this->items[$product_ord]);
				return;
			}
			}

			$str_val = $this->items[$product_ord];

			$a_val = explode($this->str_pattern,$str_val);

			$a_val[$comp] = $val;

			$str_val = implode($this->str_pattern, $a_val);

			$this->items[$product_ord] = $str_val;
       }
    }
	  
	//get comp by order of list;
	public function get_comp_item($product_ord,$comp)
    {
       if(array_key_exists($product_ord, $this->items))
       {
			if(empty($comp)) $comp = 0;

			$str_val = $this->items[$product_ord];

			$a_val = explode($this->str_pattern,$str_val);

			return $a_val[$comp];
       }
    } 
	
	public function empty_cart()
    {
		unset($this->items);
	}

	public function set_cart($items)
    {
       $this->items = $items;
    }
    
   	public function get_cart()
    {
       return $this->items;
    } 
    
	public function showlist()
    {
        $mlist = '';
    	$sub_total = 0;
    	$total = 0;
		$val = '';
      	$i = 0; 
      	foreach($this->items as $order=>$val) 
		{
      		$a_val = $this->get_itemval($order);
      		$mlist[$i]['item_order'] = $order;
      		$mlist[$i]['products_id'] = $a_val[0];
      		$mlist[$i]['item_qty'] = $a_val[1];
      		$mlist[$i]['products_name'] = $a_val[2];
      		$mlist[$i]['item_price'] = $a_val[3];
      		$mlist[$i]['item_weight'] = $a_val[4];
      		$mlist[$i]['item_comment'] = $a_val[5];
      		
      		$sub_total += $a_val[1]*$a_val[3];
      		$mlist[$i]['item_amount'] = $sub_total;
			$total += $sub_total;
      		$i++;
      	}
      	$mlist[0]['total_amount'] = $total;
        return $mlist;
    }
    
	public function check_item($item_id)
	{
		foreach($this->items as $order=>$val) 
		{
      		$a_val = $this->get_itemval($order);
      		$temp_id = $a_val[0];
      		if($item_id == $temp_id)
      			return true;		
		}
		return false;
	}
	
   	public function quickview()
    {
    	$total_amount = 0;
        $total_item = 0;

      	foreach($this->items as $order=>$val)
		{
      		$a_val = $this->get_itemval($order);
            // calc before format number
            $total_item += $a_val[1]; //qty
      		$total_amount += $a_val[1]*$a_val[3]; //qty*price
      	}
        return $data = array('total_item'=>$total_item,'total_amount'=>$total_amount);
    } 
    
	public function load_quick_cart()
	{
		if ($this->session->get('cart'))
		{		
			$cart = $this->session->get('cart');
			
			$this->set_cart($cart);
			
			$mquickcart = $this->quickview();
		} else {
			$mquickcart = array('total_item'=>0,'total_amount'=>0.00);
		}
		$mquickcart['total_value'] = $mquickcart['total_amount'];
		$mquickcart['total_amount'] = $this->format_currency($mquickcart['total_amount'],$this->site['site_currency']);
		$this->template->mquickcart = $mquickcart;
	}	
	
	//------------ Language ------------
	public function get_client_lang()
	{
		if($this->session->get('sess_client_lang')){
			return $this->session->get('sess_client_lang');
		} else
			return 1;
	}
	
	public function get_admin_lang()
	{
		if($this->session->get('sess_admin_lang')){
			return $this->session->get('sess_admin_lang');
		} else
			return 1;
	}
	
	//------------ Format ------------
	//Currency
	function format_currency($val=0, $site_lang=1)
	{
		$f = '';
		//if(!$val) return false;
		if ($val<0)
		{
			$val = abs($val);
			$f = "- ";
		}
		//if(!$val) return false;		
		if($site_lang == 1){
			//format English
			return $f.'$'.number_format($val,2,".",",");
		
		} elseif($site_lang == 2) {
			//format Korean
			return number_format($val,0,".",",").'&#50896;';
			
		} elseif($site_lang == 3) {
			//format Vietnam
			return number_format($val,0,",",".").' VND';
			
		} else {
			return $val;
		}	
	}	
	//Number
	public function format_number($val=0, $site_lang=1)
	{
		if(!$val) return false;
		
		if($site_lang == 1){
			//format English
			return number_format($val,2,".",",");
		} elseif($site_lang == 2){
			//format Vietnam
			return number_format($val,0,".",",");
		} else {
			return $val;
		}	
	}
	//Int date
	public function format_int_date($int_date,$str_format)
	{
		if(!$int_date) return false;
		return date($str_format,$int_date);
	}
	//String date
	public function format_str_date($str_date,$str_format = 'Y/m/d',$str_sep='/',$h=0,$mi=0,$s=0)
	{
		if(!$str_date) return false;
		
		$arr = explode($str_sep, $str_date);
			
		switch($str_format)
		{
			case 'Y/m/d':	list($y,$m,$d) = $arr;break;
			
			case 'm/d/Y':	list($m,$d,$y) = $arr;break;
			
			case 'n/j/Y':	list($m,$d,$y) = $arr;break;
			
			case 'd/m/Y':	list($d,$m,$y) = $arr;break;		
		}		
		return mktime($h,$mi,$s,$m,$d,$y);
	}
	//String code
	public function format_code($str_code,$str_format)
	{
		return str_pad($str_code,strlen($str_format),$str_format,STR_PAD_LEFT);
	}
	//list cateogry search
	
}